package org.ranshiyan.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Configuration
public class WebSecurityConfig extends WebMvcConfigurerAdapter {
    /**
     * 登录session key
     */
    public final static String SESSION_KEY = "user";
    @Bean
    public SecurityInterceptor getSecurityInterceptor() {
        return new SecurityInterceptor();
    }
    public void addInterceptors(InterceptorRegistry registry) {

        InterceptorRegistration interceptorRegistry = registry.addInterceptor((HandlerInterceptor) getSecurityInterceptor());
        interceptorRegistry.excludePathPatterns("/login**");
        interceptorRegistry.excludePathPatterns("/list**");
    }

    private class SecurityInterceptor extends HandlerInterceptorAdapter {
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            HttpSession session = request.getSession();
            if(session.getAttribute(SESSION_KEY)!=null){
                return true;
            }else{
                System.out.println("请先登录");
                response.sendRedirect("/login");
            }

            return true;
        }
    }

}
